package com.hcinfos.gsoo.ui;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import com.baidu.location.LocationClient;
import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Constants;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.City;
import com.hcinfos.gsoo.enity.ViewSuppSearchExt;
import com.hcinfos.gsoo.interaze.ShakeListener;
import com.hcinfos.gsoo.interaze.ShakeListener.OnShakeListener;
import com.hcinfos.gsoo.service.LocationService;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 随机获取附近商家
 * 
 * @author xi
 * 
 */
public class RandomNearActivity extends Activity implements OnClickListener {

	private ImageView shake_iv;
	private Animation anim;

	private ShakeListener mShakeListener = null;
	private Vibrator mVibrator;

	private ImageView back_iv;
	private SharePreferenceUtil util;
	private LocationClient locationClient;
	private List<ViewSuppSearchExt> resultList = null;
	private ObjectMapper objectMapper;

	private Dialog dialog;
	private Button change_btn;
	private ImageView close_iv;
	private BitmapUtils bitmapUtils;
	private BitmapDisplayConfig bigPicDisplayConfig;

	public final int DATA_SUCCESS = 0x2211;
	public final int DATA_FAIL = DATA_SUCCESS + 1;
	public final int DELAY = DATA_SUCCESS + 2;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_randomnear);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		bitmapUtils = new BitmapUtils(this);
		objectMapper = new ObjectMapper();
		resultList = new ArrayList<ViewSuppSearchExt>();
		locationClient = ((GsooApplication) getApplication()).mLocationClient;
		bigPicDisplayConfig = new BitmapDisplayConfig();
		bigPicDisplayConfig.setLoadingDrawable(getResources().getDrawable(
				R.drawable.tc_shop_default_logo));
		bigPicDisplayConfig.setLoadFailedDrawable(getResources().getDrawable(
				R.drawable.tc_shop_default_logo));
		IntentFilter filter = new IntentFilter(LocationService.LOCATION_ACTION);
		registerReceiver(locationReceiver, filter);
		util = new SharePreferenceUtil(this, "setting");
		anim = AnimationUtils.loadAnimation(this, R.anim.roll_rorate);
		shake_iv = (ImageView) findViewById(R.id.shake_iv);
		back_iv = (ImageView) findViewById(R.id.back_iv);
		back_iv.setOnClickListener(this);
		dialog = createDialog();

		// initData();
	}

	@Override
	protected void onResume() {
		super.onResume();
		LogUtil.d("wxf", "Random onResume");

		initShake();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		LogUtil.d("wxf", "Random onStop");
		if (mShakeListener != null)
			mShakeListener.stop();

		mShakeListener = null;
	}

	/**
	 * 初始化震动
	 */
	private void initShake() {
		mShakeListener = new ShakeListener(this);
		mShakeListener.setOnShakeListener(new shakeLitener());

		mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	}

	// 震动以及播放声音
	public void startPlayVibrato() {
		play();
		mVibrator.vibrate(new long[] { 500, 200, 500, 200 }, -1);
	}

	private void play() {

		MediaPlayer mediaPlayer = new MediaPlayer();
		try {
			AssetFileDescriptor fd = getResources().getAssets().openFd(
					"sound/shake_sound_male.mp3");
			mediaPlayer.setDataSource(fd.getFileDescriptor(),
					fd.getStartOffset(), fd.getLength());
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				mp.release();
			}
		});

	}

	/**
	 * 开始动画
	 * 
	 */
	private boolean isShake = false;

	public void startShakeAnim(boolean isRunning) {
		// shake_icon.setBackgroundResource(R.drawable.rol);
		if (isRunning) {
			shake_iv.startAnimation(anim);
		} else {
			shake_iv.clearAnimation();
		}

	}

	class shakeLitener implements OnShakeListener {
		@Override
		public void onShake() {

			if (dialog.isShowing())
				return;
			if (resultList != null && resultList.size() > 0) {
				if (mShakeListener == null)
					return;
				startShakeAnim(true);
				mShakeListener.stop();
				startPlayVibrato();
				Message msg = handler.obtainMessage();
				msg.what = 0x2210;
				handler.sendMessageDelayed(msg, 2000);
			} else {
				dialog.show();
				initData();
			}

		}
	}

	Handler handler = new Handler() {

		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 0x2210:

				isShake = true;
				dialog.show();
				shake_iv.clearAnimation();
				mShakeListener.start();
				mVibrator.cancel();

				if (resultList != null && resultList.size() > 0) {
					int random = (int) (Math.random() * resultList.size());
					ext = resultList.get(random);
					updateViews();
				} else {

					if (isShake) {
						Toast.makeText(RandomNearActivity.this, "附近暂无数据!", 500)
								.show();
						isShake = false;
					}

					dialog.dismiss();
				}
				break;
			case DATA_SUCCESS:
				if (resultList != null && resultList.size() > 0) {
					int random = (int) (Math.random() * resultList.size());
					ext = resultList.get(random);
					updateViews();
				} else {

					Toast.makeText(RandomNearActivity.this, "附近暂无数据!", 500)
							.show();
					dialog.dismiss();
				}
				break;
			case DATA_FAIL:
				dialog.dismiss();
				// Toast.makeText(RandomNearActivity.this, "附近暂无数据!",
				// 500).show();
				break;
			case DELAY:
				int random = (int) (Math.random() * resultList.size());
				ext = resultList.get(random);
				updateViews();
				break;
			}
		};
	};
	private ViewSuppSearchExt ext;

	private void updateViews() {
		if (ext == null)
			return;
		data_rl.setVisibility(View.VISIBLE);
		progress.setVisibility(View.GONE);
		String url = Constants.SERVER + ext.getImgAddr()
				+ Constants.IMG_THUMB_DIR + ext.getImgId() + ".jpg";
		bitmapUtils.display(icon_iv, url, bigPicDisplayConfig);
		name_tv.setText("名字: " + ext.getSuppName());
		String consumpPer = ext.getConsumptionPer() == null ? "暂无" : ("￥" + ext
				.getConsumptionPer()) + "";
		average_tv.setText("人均消费: " + consumpPer);
		double distance = ext.getDistance();
		BigDecimal dif = new BigDecimal(distance);
		double disStr = dif.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		distance_tv.setText("距离: " + disStr + "km");
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.back_iv:
			finish();
			break;
		case R.id.go_btn:
			dialog.dismiss();
			Intent intent = new Intent(RandomNearActivity.this,
					ShopDetailActivity.class);
			intent.putExtra("shopDetail", ext);
			startActivity(intent);
			break;
		case R.id.change_btn:
			handler.sendEmptyMessageDelayed(DELAY, 1500);
			data_rl.setVisibility(View.GONE);
			progress.setVisibility(View.VISIBLE);

			break;
		case R.id.close_iv:
			dialog.dismiss();
			break;

		}
	}

	private String typeId = "040b27f2e5084d7f9891898195043d80,382ae00ab4a14c90a6b9867ff5d1f863,9457105c3a6f49b78def4f1553d16858,c2a97ada018841e6a1cb71fb6efb3f63,36f76d8c3f634f6d905dfd195a815592,8bd36522dd1f4dd4a5a692b64e0b4846,1a2fce881cf64ab99815dcfa056a643e,9274ce9580764ffeb8dab7a9956fc21d,f29faee34ee84cf0adc4552d5b7474eb,083cfaf24c294251a9822700a7a9abfe,229ba7646ed94f05b5c3bc78f89090a5,1b79cb6389274fcab43aade063426436,202afa581577467ba987f5ab3686564f,4e1abe5fe6d543f3b6b6f6c33e375311,a2eef889b32e457a9d1eb7e0684c2407,aac72832fa5d4666b172ffe6dc33e3fd,04dd61f6d72b46bc834262de6e0e6506,fdda9e479c3246809200e0fc20e74e8f,4908b224188d4c23b77bfd9f9e26b162,73fa4401fdcb48e2928053ee468bea4c,d10c831a71a44137be693da9a32e6cdc,db34df71978a4041b7443af756fe6f20,efb61a225a144fa5887ef85ad1e6b3fb,52359ac526744458961a94ee67548623,2a4a5eb53ece47239015ff1d702b30f2,dbd26ecac42f40b2a78c5d0f9a1cce1b,1e7221aba3e34b16a9cb0db3eecdaea2,2409ad531a344811a2ea2cec0c448011,ffe51c07201a4505b33724da23bf989c,fdcd6fcac89541f19af4618e9c4dc78a,c9d34dc6edee4d1ca7f4cfa63842c6d0,ad472e924041410a96897761c252798f,8ccc2044f35548ab85e1746d2d59ff27,7fe93852962b414798a98416c82f2833";
	private String cityId = "";

	private void initData() {
		City city = (City) util.loadObject("city");
		try {
			if (city != null) {
				if (GsooApplication.lat == null) {
					locationClient.start();
				} else {
					cityId = city.getCityId();
					obtainList();
				}
			}
		} catch (Exception e) {

		}
	}

	private void obtainList() {
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		params.addBodyParameter("lsbaiAreaId", cityId);
		params.addBodyParameter("csrecord.lon", GsooApplication.lng + "");
		params.addBodyParameter("csrecord.lat", GsooApplication.lat + "");
		params.addBodyParameter("csrecord.kmScope", "200");
		params.addBodyParameter("csrecord.typeId", typeId);
		params.addBodyParameter("csOrder", 0 + "");
		params.addBodyParameter("page", 1 + "");
		params.addBodyParameter("rows", 20 + "");

		http.send(HttpRequest.HttpMethod.POST, Urls.NEW_SHOP_LIST, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", responseInfo.result);
						try {

							JSONObject obj = new JSONObject(responseInfo.result);
							String arrayStr = obj.getString("rows");
							int state = obj.getInt("state");
							if (state == 200) {
								resultList = objectMapper
										.readValue(
												arrayStr,
												new TypeReference<List<ViewSuppSearchExt>>() {
												});
								handler.sendEmptyMessage(DATA_SUCCESS);

							}

						} catch (Exception e) {
							LogUtil.e("wxf", e.toString());
							handler.sendEmptyMessage(DATA_FAIL);

						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(DATA_FAIL);
					}

				});

	}

	protected void onDestroy() {

		unregisterReceiver(locationReceiver);
		super.onDestroy();

	};

	BroadcastReceiver locationReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			obtainList();
		}

	};

	private TextView name_tv;
	private TextView average_tv;
	private TextView distance_tv;
	private ImageView icon_iv;
	private Button go_btn;
	private ProgressBar progress;
	private RelativeLayout data_rl;

	private Dialog createDialog() {

		LayoutInflater inflater = getLayoutInflater();
		RelativeLayout dialog_rl = (RelativeLayout) inflater.inflate(
				R.layout.random_dialog_view, null);
		Dialog dialog = new Dialog(RandomNearActivity.this, R.style.QuitDialog);
		dialog.setContentView(dialog_rl);
		progress = (ProgressBar) dialog_rl.findViewById(R.id.progress);
		data_rl = (RelativeLayout) dialog_rl.findViewById(R.id.data_rl);
		data_rl.setVisibility(View.GONE);
		progress = (ProgressBar) dialog_rl.findViewById(R.id.progress);
		name_tv = (TextView) dialog_rl.findViewById(R.id.name_tv);
		average_tv = (TextView) dialog_rl.findViewById(R.id.average_tv);
		distance_tv = (TextView) dialog_rl.findViewById(R.id.distance_tv);
		icon_iv = (ImageView) dialog_rl.findViewById(R.id.icon_iv);
		go_btn = (Button) dialog_rl.findViewById(R.id.go_btn);
		go_btn.setOnClickListener(this);
		change_btn = (Button) dialog_rl.findViewById(R.id.change_btn);
		change_btn.setOnClickListener(this);
		close_iv = (ImageView) dialog_rl.findViewById(R.id.close_iv);
		close_iv.setOnClickListener(this);

		Window dialogWindow = dialog.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(Gravity.CENTER);
		lp.width = (int) (260 * Common.PROPORTION); // 宽度
		lp.height = (int) (300 * Common.PROPORTION); // 高度
		dialogWindow.setAttributes(lp);

		return dialog;
	}

	long waitTime = 2000;
	long touchTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& KeyEvent.KEYCODE_BACK == keyCode) {
			long currentTime = System.currentTimeMillis();
			if ((currentTime - touchTime) >= waitTime) {
				Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
				touchTime = currentTime;
			} else {
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
